package org.mao.quartz;

import java.util.Date;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledFuture;

import org.apache.log4j.Logger;
import org.mao.forum.job.GrabPostingImageJob;
import org.mao.forum.service.ForumTaskService;
import org.mao.parser.ForumParserProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import com.google.common.collect.Maps;

@Configuration
@EnableScheduling
public class QuartzTaskSchedule implements SchedulingConfigurer {

	private static Logger logger = Logger.getLogger(QuartzTaskSchedule.class);

	private ThreadPoolTaskScheduler scheduler = null;

	public static ConcurrentMap<Integer, ScheduledFuture<?>> forumTaskUniqueList = Maps.newConcurrentMap();

	@Autowired
	private ForumTaskService forumTaskService;
	
	@Autowired
	private ForumParserProxy forumParserProxy;

	public void createSchedule(Integer taskId, Date startTime, Integer period) {
		logger.info("QuartzTaskSchedule start createSchedule[taskId=" + taskId + "]");
		if (QuartzTaskSchedule.forumTaskUniqueList.containsKey(taskId)) {
			logger.info("QuartzTaskSchedule schedule exist!");
			return;
		}
		GrabPostingImageJob grabPostingImageJob = new GrabPostingImageJob(taskId, forumTaskService, forumParserProxy);
		ScheduledFuture<?> scheduledFuture = null;
		if (startTime == null) {
			if (period == null) {
				scheduledFuture = scheduler.schedule(grabPostingImageJob, new Date());
			} else {
				scheduledFuture = scheduler.scheduleWithFixedDelay(grabPostingImageJob, period * 1000);
			}
		} else {
			if (period == null) {
				scheduledFuture = scheduler.schedule(grabPostingImageJob, startTime);
			} else {
				scheduledFuture = scheduler.scheduleWithFixedDelay(grabPostingImageJob, startTime, period * 1000);
			}
		}
		forumTaskUniqueList.put(taskId, scheduledFuture);
	}

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		logger.info("QuartzTaskSchedule.configureTasks");

		scheduler = new ThreadPoolTaskScheduler();
		scheduler.setPoolSize(5);
		scheduler.initialize();
		taskRegistrar.setTaskScheduler(scheduler);
	}

}
